<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="资产编号" prop="assetNo">
        <el-input
          v-model="queryParams.assetNo"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备号" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetList" :fit="true" class="responsive-table">
      <el-table-column label="资产编号" align="center" prop="assetNo" :min-width="120" show-overflow-tooltip resizable />
      <el-table-column label="设备号" align="center" prop="deviceNo" :min-width="140" show-overflow-tooltip resizable />
      <el-table-column label="设备名称" align="center" prop="assetName" :min-width="220" show-overflow-tooltip resizable />
      <el-table-column label="位置" align="center" prop="location" :min-width="160" show-overflow-tooltip resizable />
      <el-table-column label="规格型号" align="center" prop="modelNo" :min-width="160" show-overflow-tooltip resizable />
      <el-table-column label="设备类型" align="center" prop="equipmentTypeCode" width="120">
        <template slot-scope="scope">
          <span>{{ getEquipmentTypeName(scope.row.equipmentTypeCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用部门" align="center" prop="deptName" :min-width="140" show-overflow-tooltip resizable />
      <el-table-column label="购入日期" align="center" prop="purchaseDate" :min-width="170" resizable>
        <template slot-scope="scope">
          <span>{{ formatDateTime(scope.row.purchaseDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人员" align="center" prop="operatorName" :min-width="120" show-overflow-tooltip resizable />
      <el-table-column label="状态" align="center" prop="statusCode" :min-width="100" resizable>
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.statusCode)">
            {{ getStatusName(scope.row.statusCode) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :min-width="220" resizable>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: #f56c6c;"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-dropdown @command="(command) => handleStatusCommand(command, scope.row)" trigger="click">
            <el-button size="mini" type="text">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="view">查看</el-dropdown-item>
              <el-dropdown-item command="fault" v-if="scope.row.statusCode !== 'ASSET_STATUS_002'">故障</el-dropdown-item>
              <el-dropdown-item command="scrap" v-if="scope.row.statusCode !== 'ASSET_STATUS_004'">报废</el-dropdown-item>
              <el-dropdown-item command="idle" v-if="scope.row.statusCode !== 'ASSET_STATUS_003'">闲置</el-dropdown-item>
              <el-dropdown-item command="enable" v-if="scope.row.statusCode === 'ASSET_STATUS_003' || scope.row.statusCode === 'ASSET_STATUS_004'">启用</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产编号" prop="assetNo">
              <el-input v-model="form.assetNo" placeholder="请输入资产编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备号" prop="deviceNo">
              <el-input v-model="form.deviceNo" placeholder="请输入设备号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeCode">
              <el-select v-model="form.equipmentTypeCode" placeholder="请选择设备类型">
                <el-option v-for="type in equipmentTypeOptions" :key="type.dictValue" :label="type.dictLabel" :value="type.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入使用部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入位置" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="modelNo">
              <el-input v-model="form.modelNo" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购入日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="datetime"
                placeholder="请选择购入日期"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handlePurchaseDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投产日期" prop="commissioningDate">
              <el-date-picker
                v-model="form.commissioningDate"
                type="datetime"
                placeholder="请选择投产日期"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleCommissioningDateChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作人员" prop="operatorName">
              <el-input v-model="form.operatorName" placeholder="操作人员" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="statusCode">
              <el-select v-model="form.statusCode" placeholder="请选择状态">
                <el-option
                  v-for="status in statusOptions"
                  :key="status.dictValue"
                  :label="status.dictLabel"
                  :value="status.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 模具图片 -->
        <ImageUpload
          ref="imageUpload"
          v-model="form.images"
          title="模具图片"
          :max-count="5"
          :max-size="2"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAsset, getAsset, delAsset, addAsset, updateAsset, exportAsset, updateAssetStatus } from "@/api/asset/asset";
import { getDicts } from "@/api/dict/data";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";
import ImageUpload from "@/views/components/ImageUpload.vue";
import RightToolbar from '@/components/RightToolbar'

export default {
  name: "Asset",
  components: {
    ImageUpload,
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产表格数据
      assetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否编辑模式
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetNo: null,
        deviceNo: null,
        name: null,
        equipmentTypeCode: null,
        deptName: null,
        statusCode: null
      },
      // 设备类型选项
      equipmentTypeOptions: [],
      // 状态选项
      statusOptions: [],
      // 表单参数
      form: {
        assetNo: null,
        assetName: null,
        deviceNo: null,
        location: null,
        modelNo: null,
        equipmentTypeCode: null,
        brand: null,
        manufacturer: null,
        supplierName: null,
        deptName: null,
        operatorName: null,
        purchaseDate: null,
        commissioningDate: null,
        statusCode: "ASSET_STATUS_001",
        images: []
      },
      // 表单校验
      rules: {
        assetNo: [{ required: true, message: "资产编号不能为空", trigger: "blur" }],
        deviceNo: [{ required: true, message: "设备号不能为空", trigger: "blur" }],
        assetName: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
        location: [{ required: true, message: "位置不能为空", trigger: "blur" }],
        modelNo: [{ required: true, message: "规格型号不能为空", trigger: "blur" }],
        equipmentTypeCode: [{ required: true, message: "设备类型不能为空", trigger: "change" }],
        brand: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
        deptName: [{ required: true, message: "使用部门不能为空", trigger: "blur" }],
        manufacturer: [{ required: true, message: "制造商不能为空", trigger: "blur" }],
        supplierName: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
        operatorName: [{ required: true, message: "操作人员不能为空", trigger: "blur" }],
        purchaseDate: [
          { required: true, message: "购入日期不能为空", trigger: "change" }
        ],
        commissioningDate: [
          { required: true, message: "投产日期不能为空", trigger: "change" },
          { validator: this.validateCommissioningDate, trigger: "change" }
        ]
      }
    };
  },
  async created() {
    await Promise.all([
      this.getEquipmentTypeOptions(),
      this.getStatusOptions()
    ])
    await this.getList()
  },
  methods: {
    /** 获取当前登录用户名 */
    getCurrentUserName() {
      try {
        const store = this.$store;
        return (store && store.getters && store.getters.name) || '';
      } catch(e) {
        return '';
      }
    },
    /** 查询资产列表 */
    getList() {
      this.loading = true;
      return listAsset(this.queryParams).then(response => {
        const rows = response.rows || []
        const typeMap = new Map((this.equipmentTypeOptions || []).map(t => [t.dictValue, t.dictLabel]))
        const statusMap = new Map((this.statusOptions || []).map(s => [s.dictValue, s.dictLabel]))
        this.assetList = rows.map(r => ({
          ...r,
          equipmentTypeName: typeMap.get(r.equipmentTypeCode) || r.equipmentTypeCode,
          statusName: statusMap.get(r.statusCode) || r.statusCode
        }))
        this.total = response.total || rows.length
      }).finally(()=>{
        this.loading = false
      })
    },
    /** 获取设备类型选项 */
    getEquipmentTypeOptions() {
      return request({ url: '/system/type/list', method: 'get', params: { pageNum: 1, pageSize: 9999, enabled: 1 } }).then(response => {
        this.equipmentTypeOptions = (response.rows || []).map(item => ({
          dictValue: item.code,
          dictLabel: item.name
        }));
      }).catch(()=>{ this.equipmentTypeOptions = [] })
    },
    /** 获取状态选项 */
    getStatusOptions() {
      return request({ url: '/system/status/asset/list', method: 'get', params: { pageNum: 1, pageSize: 9999, enabled: 1 } }).then(response => {
        this.statusOptions = (response.rows || []).map(item => ({
          dictValue: item.code,
          dictLabel: item.name
        }));
      }).catch(() => {
        // 兜底数据
        this.statusOptions = [
          { dictValue: 'ASSET_STATUS_001', dictLabel: '正常' },
          { dictValue: 'ASSET_STATUS_002', dictLabel: '故障' },
          { dictValue: 'ASSET_STATUS_003', dictLabel: '闲置' },
          { dictValue: 'ASSET_STATUS_004', dictLabel: '报废' }
        ];
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        assetNo: null,
        assetName: null,
        deviceNo: null,
        location: null,
        modelNo: null,
        equipmentTypeCode: null,
        brand: null,
        manufacturer: null,
        supplierName: null,
        deptName: null,
        operatorName: null,
        purchaseDate: null,
        commissioningDate: null,
        statusCode: "ASSET_STATUS_001",
        images: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      // 自动填充当前登录用户名
      this.form.operatorName = this.getCurrentUserName();
      this.open = true;
      this.title = "添加资产";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;
      const assetNo = row.assetNo;
      getAsset(assetNo).then(response => {
        this.form = response.data;
        // 回显图片：将 imageUrls(JSON字符串/数组) 转为 el-upload 的 file-list
        const urls = Array.isArray(response.data.imageUrls)
          ? response.data.imageUrls
          : (response.data.imageUrls ? (()=>{ try { return JSON.parse(response.data.imageUrls) } catch(e){ return [] } })() : [])
        
        // 使用公共组件的方法初始化图片
        this.$nextTick(() => {
          const imageUploadRef = this.$refs.imageUpload
          if (imageUploadRef) {
            imageUploadRef.initFromUrls(urls)
          }
        })
        
        this.open = true;
        this.title = "修改资产";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assetNos = row.assetNo;
      this.$modal.confirm('是否确认删除资产编号为"' + assetNos + '"的数据项？').then(function() {
        return delAsset(assetNos)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 使用公共组件的方法获取存储URL列表
          const imageUploadRef = this.$refs.imageUpload
          const storedList = imageUploadRef ? imageUploadRef.getStoredUrls() : []
          const payload = { ...this.form, imageUrls: JSON.stringify(storedList) }
          
          if (this.isEdit) {
            updateAsset(payload).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAsset(payload).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 状态管理操作 */
    handleStatusCommand(command, row) {
      switch (command) {
        case 'view':
          this.$router.push({ path: `/asset/detail/${row.assetNo}` })
          break;
        case 'fault':
          this.handleStatusChange(row, 'ASSET_STATUS_002', '故障')
          break;
        case 'scrap':
          this.handleStatusChange(row, 'ASSET_STATUS_004', '报废')
          break;
        case 'idle':
          this.handleStatusChange(row, 'ASSET_STATUS_003', '闲置')
          break;
        case 'enable':
          this.handleStatusChange(row, 'ASSET_STATUS_001', '启用')
          break;
      }
    },
    /** 状态变更 */
    handleStatusChange(row, statusCode, statusName) {
      this.$modal.confirm(`是否确认将资产"${row.assetName}"状态变更为"${statusName}"？`).then(() => {
        return updateAssetStatus(row.assetNo, statusCode)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("状态变更成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/asset/export', {
        ...this.queryParams
      }, `asset_${new Date().getTime()}.xlsx`)
    },
    /** 切换搜索显示 */
    toggleSearch() {
      this.showSearch = !this.showSearch
    },
    /** 获取设备类型名称 */
    getEquipmentTypeName(code) {
      if (!code) return '';
      const type = this.equipmentTypeOptions.find(t => t.dictValue === code);
      return type ? type.dictLabel : code;
    },
    /** 获取部门名称 */
    /** 获取状态名称 */
    getStatusName(code) {
      if (!code) return '';
      const status = this.statusOptions.find(s => s.dictValue === code);
      return status ? status.dictLabel : code;
    },
    /** 获取状态标签类型 */
    getStatusTagType(code) {
      const typeMap = {
        'ASSET_STATUS_001': 'success', // 正常
        'ASSET_STATUS_002': 'danger',  // 故障
        'ASSET_STATUS_003': 'warning', // 闲置
        'ASSET_STATUS_004': 'danger'   // 报废
      }
      return typeMap[code] || 'info'
    },
    /** 监听购入日期变化，触发投产日期验证 */
    handlePurchaseDateChange() {
      // 如果已经填写了投产日期，则触发验证
      if (this.form.commissioningDate) {
        this.$refs.form.validateField('commissioningDate');
      }
    },
    /** 监听投产日期变化，触发投产日期验证 */
    handleCommissioningDateChange() {
      // 当投产日期变化时，触发验证
      if (this.form.commissioningDate) {
        this.$refs.form.validateField('commissioningDate');
      }
    },
    /** 验证投产日期必须在购入日期之后 */
    validateCommissioningDate(rule, value, callback) {
      if (value && this.form.purchaseDate) {
        const purchaseDate = new Date(this.form.purchaseDate);
        const commissioningDate = new Date(value);
        if (commissioningDate.getTime() < purchaseDate.getTime()) {
          callback(new Error("投产日期必须在购入日期之后"));
          return;
        }
      }
      callback();
    },
    /** 格式化日期时间显示完整格式 */
    formatDateTime(date) {
      if (!date) return '';

      let dateObj = null;

      // 处理不同类型的输入
      if (typeof date === 'string') {
        // 如果已经是完整的日期时间格式，直接返回
        if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date)) {
          return date;
        }
        // 如果只有日期部分，添加默认时间
        if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
          return date + ' 00:00:00';
        }
        // 如果包含T（ISO格式），转换为标准格式
        if (date.includes('T')) {
          const cleanDate = date.replace('T', ' ').replace(/\.\d{3}Z?$/, '');
          return cleanDate;
        }
        // 尝试解析其他格式的字符串
        dateObj = new Date(date);
      } else if (date instanceof Date) {
        dateObj = date;
      } else if (typeof date === 'number') {
        dateObj = new Date(date);
      }

      // 如果成功创建了Date对象，格式化为标准格式
      if (dateObj && !isNaN(dateObj.getTime())) {
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        const hours = String(dateObj.getHours()).padStart(2, '0');
        const minutes = String(dateObj.getMinutes()).padStart(2, '0');
        const seconds = String(dateObj.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }

      // 最后尝试使用parseTime函数格式化
      try {
        return this.parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}');
      } catch (e) {
        return '';
      }
    }
  }
};
</script>

<style scoped>
.responsive-table .el-table__header-wrapper table,
.responsive-table .el-table__body-wrapper table {
  table-layout: fixed;
  width: 100%;
}
.responsive-table .el-table__body-wrapper { overflow-x: auto; }
.responsive-table .cell { white-space: nowrap; }
.operation-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.search-buttons {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  align-items: center;
}

/* 统一按钮样式 */
.operation-buttons .el-button {
  border-radius: 4px;
  font-weight: 500;
}

.operation-buttons .el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.operation-buttons .el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
